﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller;
using Entity;
using AjaxControlToolkit;

namespace Web
{
    public partial class MakeCustomerPO : System.Web.UI.Page
    {
        Helper helper = new Helper();
                
                
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //clear the session  dirty data
                Session["CustomerPOItemList"] = null;

                //bind customers
                CustomerController cc=new CustomerController();
                IList<CustomerEntity> customerEntities = cc.finAllCustomers();
                CustomerDropDownList.DataSource = customerEntities;
                CustomerDropDownList.DataTextField = "ShortName";
                CustomerDropDownList.DataValueField = "Id";
                CustomerDropDownList.DataBind();
                int custormerId = Convert.ToInt32(CustomerDropDownList.SelectedValue);

                CustomerEntity customerEntity = cc.FindCustomerByCustomerId(custormerId);
                
                string address1 = "";
                string address2 = "";
                string address3 = "";

                ZipCodeTextBox.Text = customerEntity.ZipCode;

                string[] address = customerEntity.Address.Split(',');
                if (address.Length == 3)
                {
                    address1 = address[0];
                    address2 = address[1];
                    address3 = address[2];
                }
                else if (address.Length == 2)
                {
                    address1 = address[0];
                    address2 = address[1];
                }
                else if (address.Length == 1)
                {
                    address1 = address[0];
                }
                ShipToTextBox1.Text = address1;
                ShipToTextBox2.Text = address2;
                ShipToTextBox3.Text = address3;
                

                //bind products
                ProductController productController=new ProductController();
                IList<ProductEntity> productEntities = productController.FindAllProductEntities();
                ProductDropDownList.DataSource = productEntities;
                ProductDropDownList.DataTextField = "ProductNoAndRevision";
                ProductDropDownList.DataValueField = "Id";
                ProductDropDownList.DataBind();
                ProductDropDownList.Items.Insert(0, new ListItem("--Select Product--", "0")); 
                RequestedDateTextBox_CalendarExtender0.SelectedDate = System.DateTime.Now;
                
                double total=0;
                foreach (GridViewRow r in CustomerPOItemGridView.Rows)
                {
                    total = total+Convert.ToDouble(r.Cells[5].Text);
                    
                }
                TotalLabel.Text = total.ToString()+" USD";

            }

            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }
        protected void ProductDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProductDropDownList.SelectedIndex != 0)
            {
                int productId = Convert.ToInt32(ProductDropDownList.SelectedValue);
                ProductController productController = new ProductController();
                ProductEntity productEntity = productController.FindProductById(productId);
                ProductNameLabel.Text = productEntity.Name;
            }
            else
            {
                ProductNameLabel.Text = "";
            }

        }
        IList<CustomerPOItemEntity> customerPoItemEntities = new List<CustomerPOItemEntity>();
        protected void InsertButton_Click(object sender, EventArgs e)
        {
            if (Session["CustomerPOItemList"] == null && ProductDropDownList.SelectedIndex!=0)
            {
                CustomerPOItemEntity customerPoItemEntity = new CustomerPOItemEntity();
                ProductController productController = new ProductController();
                ProductEntity productEntity =
                    productController.FindProductById(Convert.ToInt32(ProductDropDownList.SelectedValue));


                customerPoItemEntity.ProductId = productEntity.Id;
                customerPoItemEntity.ProductName = productEntity.Name;
                customerPoItemEntity.ProductNo = productEntity.No;
                customerPoItemEntity.Revision = productEntity.Revision;
                customerPoItemEntity.RequestDate = Convert.ToDateTime(RequestedDateTextBox.Text);
                customerPoItemEntity.RequestQty = Convert.ToInt32(QuantityTextBox.Text);
                customerPoItemEntity.Lot = Convert.ToInt32(LotTextBox.Text);
                customerPoItemEntity.Price = Convert.ToDecimal(NetPriceTextBox.Text);
                customerPoItemEntity.Amount = customerPoItemEntity.Price*customerPoItemEntity.RequestQty;

                customerPoItemEntity.FormatDate = customerPoItemEntity.RequestDate.ToString("d MMM, yyyy");
                customerPoItemEntities.Add(customerPoItemEntity);
                
            }
            else
            {
                if (ProductDropDownList.SelectedIndex != 0)
                {
                    customerPoItemEntities = Session["CustomerPOItemList"] as IList<CustomerPOItemEntity>;
                    CustomerPOItemEntity customerPoItemEntity = new CustomerPOItemEntity();
                    ProductController productController = new ProductController();
                    ProductEntity productEntity =
                        productController.FindProductById(Convert.ToInt32(ProductDropDownList.SelectedValue));


                    customerPoItemEntity.ProductId = productEntity.Id;
                    customerPoItemEntity.ProductName = productEntity.Name;
                    customerPoItemEntity.ProductNo = productEntity.No;
                    customerPoItemEntity.Revision = productEntity.Revision;
                    customerPoItemEntity.RequestDate = Convert.ToDateTime(RequestedDateTextBox.Text);
                    customerPoItemEntity.RequestQty = Convert.ToInt32(QuantityTextBox.Text);
                    customerPoItemEntity.Lot = Convert.ToInt32(LotTextBox.Text);
                    customerPoItemEntity.Price = Convert.ToDecimal(NetPriceTextBox.Text);
                    customerPoItemEntity.Amount = customerPoItemEntity.Price * customerPoItemEntity.RequestQty;
                    customerPoItemEntity.FormatDate = customerPoItemEntity.RequestDate.ToString("d MMM, yyyy");

                    customerPoItemEntities.Add(customerPoItemEntity);
                }
                else
                {
                    Session["FlashMessage"] = "Error: No Product Selected!";
                    Session["FlashMessageType"] = "error";
                }


            }
            //create po item list session
            Session["CustomerPOItemList"] = customerPoItemEntities;
            CustomerPOItemGridView.DataSource = Session["CustomerPOItemList"] as IList<CustomerPOItemEntity>;
            CustomerPOItemGridView.DataBind();
            
            decimal totalAmount = 0;
            foreach (CustomerPOItemEntity c in customerPoItemEntities)
            {
                totalAmount += c.Amount;
            }

            TotalLabel.Text = totalAmount.ToString();

        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            CustomerPOController customerPoController = new CustomerPOController();
            string newPONo = this.PONumberTextBox.Text.Trim();
            string msg = "";
            bool poNoAvailable = customerPoController.CheckCustomerPONoAvailability(newPONo,ref msg);
            if (CustomerPOItemGridView.Rows.Count > 0 && poNoAvailable)
            {
                CustomerPOEntity customerPoEntity = new CustomerPOEntity();
                CustomerPOItemController customerPoItemController=new CustomerPOItemController();
                customerPoEntity.Address = ShipToTextBox1.Text + ", " + ShipToTextBox2.Text + ", " + ShipToTextBox3.Text;
                customerPoEntity.ApprovedBy = 1;
                customerPoEntity.Attention = "";
                customerPoEntity.CreatedBy = 1;
                customerPoEntity.CustId = 1;
                customerPoEntity.Date = DateTime.Parse(PODateTextBox.Text);
                customerPoEntity.Fax = "";
                customerPoEntity.No = PONumberTextBox.Text;
                customerPoEntity.Type = POTypeRadioButtonList.SelectedValue;
                customerPoEntity.Phone = "";
                customerPoEntity.Reference = ReferenceTextBox.Text;
                customerPoEntity.Remark = RemarkTextBox.Text;
                customerPoEntity.Status = "new";
                customerPoEntity.ZipCode = ZipCodeTextBox.Text;
                customerPoEntity.TotalQty = Convert.ToInt32(TotalQtyTextBox.Text);

                int customerPOId=customerPoController.addCustomerPO(customerPoEntity);
                foreach (GridViewRow r in CustomerPOItemGridView.Rows)
                {
                    //construct a customer PO Item entity
                    CustomerPOItemEntity customerPoItemEntity = new CustomerPOItemEntity();
                    customerPoItemEntity.CompleteQty = 0;
                    customerPoItemEntity.Lot = Convert.ToInt32(((TextBox) r.FindControl("LotTextBox")).Text);
                    customerPoItemEntity.Price = Convert.ToDecimal(((TextBox)r.FindControl("PriceTextBox")).Text);
                    customerPoItemEntity.ProductId = int.Parse(((HiddenField)r.FindControl("ProductIdHiddenField")).Value);
                    customerPoItemEntity.Remark = "";
                    customerPoItemEntity.RequestDate = Convert.ToDateTime(((TextBox)r.FindControl("RequestedDateTextBox")).Text);
                    customerPoItemEntity.RequestQty = Convert.ToInt32(((TextBox)r.FindControl("RequestQtyTextBox")).Text);
                    customerPoItemEntity.Status = "new";
                    customerPoItemEntity.CustPOId = customerPOId;
                    //insert this customer PO item entity
                    customerPoItemController.addCustomerPoItem(customerPoItemEntity);
                    //update oder status by order Id
                    //int orderId = int.Parse(((HiddenField) r.FindControl("OrderIdHiddenField")).Value);
                    //string status = "customer PO";
                    //OrdersController ordersController=new OrdersController();
                    //ordersController.updateOrderStatusByOrderId(orderId,status);
                }


                Session["FlashMessage"] = "Success: Add Customer PO Successful!";
                Session["FlashMessageType"] = "success";
                Session["CustomerPOItemList"]= null;

            }
            else
            {
                if(msg!="")
                {
                    Session["FlashMessage"] = msg;
                    Session["FlashMessageType"] = "error";
                }
                else
                {
                    Session["FlashMessage"] = "Error: No Item!";
                    Session["FlashMessageType"] = "error";
                }

            }
            //Session["OrderEntities"] = null;
            //ClientScript.RegisterStartupScript(this.Page.GetType(), "Add Customer PO Successful!", "alert('Add Customer PO Successful!')", true);
            
        }

        protected void SameDateCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (SameDateCheckBox.Checked)
            {
                TextBox dateTxt=new TextBox();
               
                foreach (GridViewRow r in CustomerPOItemGridView.Rows)
                {
                    dateTxt = (TextBox) r.FindControl("RequestedDateTextBox");
                    string date = "";
                    if (dateTxt.Text.Length > 0)
                    {
                        date = dateTxt.Text;

                    }
                    dateTxt.Text = date;
                    break;
                }
                foreach (GridViewRow r in CustomerPOItemGridView.Rows)
                {
                    if (dateTxt.Text.Length > 0)
                    {
                        ((TextBox) r.FindControl("RequestedDateTextBox")).Text = dateTxt.Text;
                    }
                }

            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
            customerPoItemEntities = Session["CustomerPOItemList"] as IList<CustomerPOItemEntity>;
            foreach (GridViewRow r in CustomerPOItemGridView.Rows)
            {
                if (r.RowIndex == rowIndex)
                {

                    //HiddenField productIdlabel = (HiddenField)CustomerPOItemGridView.Rows[rowIndex].Cells[0].FindControl("ProductIdHiddenField");
                    //int productId = Convert.ToInt32(productIdlabel.Value);
                    if (customerPoItemEntities != null)
                    {
                        for (int i = 0; i <= customerPoItemEntities.Count;i++ )
                        {
                            if (i==rowIndex)
                            {
                                customerPoItemEntities.RemoveAt(i);
                            }

                        }
                    }
                }
                
            }
            Session["CustomerPOItemList"] = customerPoItemEntities;
            CustomerPOItemGridView.DataSource = Session["CustomerPOItemList"] as IList<CustomerPOItemEntity>;
            CustomerPOItemGridView.DataBind();
            decimal totalAmount = 0;
            foreach (CustomerPOItemEntity c in customerPoItemEntities)
            {
                totalAmount += c.Amount;
            }

            TotalLabel.Text = totalAmount.ToString() + " USD";
        }

        protected void CustomerDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int custormerId = Convert.ToInt32(CustomerDropDownList.SelectedValue);
            CustomerController customerController=new CustomerController();
            CustomerEntity customerEntity = customerController.FindCustomerByCustomerId(custormerId);
            
            string address1="";
            string address2="";
            string address3="";
            
            ZipCodeTextBox.Text = customerEntity.ZipCode;

            string[] address = customerEntity.Address.Split(',');
            if(address.Length==3)
            {
                address1 = address[0];
                address2 = address[1];
                address3 = address[2];
            }
            if(address.Length==2)
            {
                address1 = address[0];
                address2 = address[1];
            }
            if (address.Length == 1)
            {
                address1 = address[0];
            }
            ShipToTextBox1.Text = address1;
            ShipToTextBox2.Text = address2;
            ShipToTextBox3.Text = address3;
        }

        





        
    }
}